/*
 * 文件名： ScoreShopListFragment.java
 * 描    述：MainActivity -- 积分商城--列表页
 * 时    间：2015-3-25 下午5:47:21
 * 版    本：V1.0
 */

package com.miguo.activity.fragment;

import android.app.Activity;
import android.content.Intent;
import android.graphics.Paint;
import android.graphics.drawable.ColorDrawable;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.text.SpannableString;
import android.text.Spanned;
import android.text.style.AbsoluteSizeSpan;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.miguo.activity.ScoreShopDetailExchangeActivity;
import com.miguo.activity.base.BaseFragment;
import com.miguo.app.AppConfig;
import com.miguo.bean.ChouJiangGoodsBean;
import com.miguo.framework.component.BaseStatusView;
import com.miguo.framework.request.FailData;
import com.miguo.framework.request.JsonData;
import com.miguo.framework.utils.Toast;
import com.miguo.framework.view.pulltorefresh.PullToRefreshBase;
import com.miguo.framework.view.pulltorefresh.PullToRefreshListView;
import com.miguo.http.HttpClient;
import com.miguo.http.Url;
import com.miguo.http.callback.AjaxCallBack;
import com.miguo.plugins.Statistics;
import com.miguo.ui.R;
import com.miguo.utils.Options;
import com.miguo.utils.ScoreShopUitl;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

public class ScoreShopExchangeFragment extends BaseFragment implements PullToRefreshBase.OnRefreshListenerTwo<ListView>, View.OnClickListener {

    private View view;

    private ArrayList<ChouJiangGoodsBean> list = new ArrayList<ChouJiangGoodsBean>();
    private ExchangeAdapter adapter;
    private ImageLoader imageLoader;
    private DisplayImageOptions imageOptions;
    private AjaxCallBack ajaxCallBack;

    private PullToRefreshListView pullToRefreshView;
    private ListView listView;
    private int pageSize = 1;
    private int page = 1;
    /**
     * 是否是刷新操作
     */
    private boolean isRefresh = false;

    public static ScoreShopExchangeFragment newInstance() {
        ScoreShopExchangeFragment fragment = new ScoreShopExchangeFragment();
        return fragment;
    }

    @Override
    public void onAttach(Activity activity) {
        super.onAttach(activity);
    }

    @Override
    public void onViewCreated(View view, Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        findViewById();
        initView();
    }

    private RelativeLayout mContent;
    private BaseStatusView BaseStatus;

    private void findViewById() {
        mContent = (RelativeLayout) view.findViewById(R.id.content_view);
        BaseStatus = (BaseStatusView) view.findViewById(R.id.base_status_view);
        BaseStatus.setContentView(mContent);
        BaseStatus.getRefreshView().setOnClickListener(this);
        BaseStatus.getNetworkView().setOnClickListener(this);

        pullToRefreshView = (PullToRefreshListView) view.findViewById(R.id.scoreShop_list);
    }

    private void initView() {
        adapter = new ExchangeAdapter();
        imageLoader = ImageLoader.getInstance();
        imageOptions = Options.getFadeOptions();

        listView = pullToRefreshView.getRefreshableView();
        Drawable divider = new ColorDrawable(0xdddddddd);
        listView.setDivider(divider);
        listView.setDividerHeight(1);
        listView.setAdapter(adapter);
        // 去除上拉下拉的箭头
        pullToRefreshView.setShowIndicator(false);
        // 设置监听器
        pullToRefreshView.setOnRefreshListener(this);
        initAjaxCallBack();
        getData();
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        view = inflater.inflate(R.layout.fragment_score_shop_list, container,
                false);
        return view;
    }

    @Override
    public void onPullDownToRefresh(PullToRefreshBase<ListView> refreshView) {
        page = 1;
        isRefresh = true;
        getData();
    }

    @Override
    public void onPullUpToRefresh(PullToRefreshBase<ListView> refreshView) {
        if (pageSize >= page + 1) {
            page++;
            isRefresh = false;
            getData();
        } else {
            Toast.show(mContext, "已经到底了!");
            pullToRefreshView.onRefreshComplete();
        }
    }

    private void initAjaxCallBack() {
        ajaxCallBack = new AjaxCallBack(getActivity()) {
            @Override
            public void onRequestFinish(JsonData json) {
                super.onRequestFinish(json);
                pullToRefreshView.onRefreshComplete();
                if (json.optInt("status") == 200) {
                    JsonData data = json.optJson("data");
                    JsonData jpage = data.optJson("page");
                    pageSize = jpage.optInt("page_size");
                    JsonData item = data.optJson("item");
                    if (isRefresh && list.size() > 0) {
                        list.clear();
                    }
                    list.addAll(ScoreShopUitl.ParserList(item));
                    adapter.notifyDataSetChanged();
                    BaseStatus.setRefreshVisibility(View.GONE);
                } else {
                    page--;
                    BaseStatus.setRefreshVisibility(View.VISIBLE);
                    Toast.show(mContext, json.optString("info"));
                }
            }

            @Override
            public void onRequestFail(FailData data) {
                super.onRequestFail(data);
                BaseStatus.setRefreshVisibility(View.VISIBLE);
                pullToRefreshView.onRefreshComplete();
                super.onRequestFail(data);
            }
        };

    }

    private void getData() {
        Map<String, String> param = new HashMap<String, String>();
        param.put("page", String.valueOf(page));
        HttpClient.post(Url.toRoute(Url.Exchange.List, 1), param, ajaxCallBack);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.refresh_rl:
            case R.id.network_error_ll:
                this.getData();
                break;
        }
    }

    private class ExchangeAdapter extends BaseAdapter {
        private LayoutInflater inflater;

        public ExchangeAdapter() {
            inflater = LayoutInflater.from(getActivity());
        }

        @Override
        public int getCount() {
            return list.size();
        }

        @Override
        public ChouJiangGoodsBean getItem(int position) {
            return list.get(position);
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override
        public View getView(final int position, View convertView, ViewGroup parent) {
            ViewHolder holder = null;
            if (convertView == null) {
                convertView = inflater.inflate(R.layout.list_score_shop_exchange, parent, false);
                holder = new ViewHolder();
                holder.img = (ImageView) convertView.findViewById(R.id.exchange_img_iv);
                holder.title = (TextView) convertView.findViewById(R.id.exchange_title_tv);
                holder.score = (TextView) convertView.findViewById(R.id.exchange_score_tv);
                holder.price = (TextView) convertView.findViewById(R.id.exchange_price_tv);
                holder.count = (TextView) convertView.findViewById(R.id.exchange_count_tv);
                holder.progress = (ProgressBar) convertView.findViewById(R.id.exchange_count_progress);
                convertView.setTag(holder);
            } else {
                holder = (ViewHolder) convertView.getTag();
            }

            ChouJiangGoodsBean bean = getItem(position);
            imageLoader.displayImage(bean.img, holder.img, imageOptions);
            holder.title.setText(bean.name);

            String src = bean.integral + "积分";
            SpannableString sb = new SpannableString(src);
            sb.setSpan(new AbsoluteSizeSpan(12, true), src.indexOf("积"),
                    src.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
            holder.score.setText(sb);

            holder.price.getPaint().setFlags(Paint.STRIKE_THRU_TEXT_FLAG);
            holder.price.getPaint().setAntiAlias(true);
            holder.price.setText("价格￥" + bean.price + "元");

            int max = Integer.valueOf(bean.count) + Integer.valueOf(bean.stock);
            holder.progress.setMax(max);
            holder.progress.setProgress(Integer.valueOf(bean.count));

            holder.count.setText("剩余" + (null == bean.stock ? "0" : bean.stock));

            convertView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    Intent intent = new Intent(getActivity(), ScoreShopDetailExchangeActivity.class);
                    intent.putExtra("bean", list.get(position));
                    startActivity(intent);
                    Statistics.onTrackCustomClick(getActivity(), AppConfig.STATISTICS.EVENT_NAME_44);
                }
            });
            return convertView;
        }
    }

    class ViewHolder {
        TextView title, score, price, count;
        ImageView img;
        ProgressBar progress;
    }

}
